package com.xz;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * @author XZ
 * @create 2021-10-16 20:54
 * https://leetcode-cn.com/problems/binary-tree-preorder-traversal/comments/
 * 失败
 */
public class _144_二叉树的前序遍历 {
    //方法一：用递归来写，调用private方法重点是List的传递
    public List<Integer> preorderTraversal1(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        perOrderTraversal(root,list);
        return list;
    }

    private void perOrderTraversal(TreeNode node,List list) {
        if (node == null) return;
        list.add(node.val);
        perOrderTraversal(node.left,list);
        perOrderTraversal(node.right,list);
    }

    //方法二：使用遍历
    public List<Integer> preorderTraversal(TreeNode root){
        List<Integer> list = new ArrayList<>();
        if (root == null) {
            return list;
        }
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        while (!stack.isEmpty()) {
            TreeNode node = stack.pop();
            list.add(node.val);
            if (node.right != null) {
                stack.push(node.right);
            }
            if (node.left != null) {
                stack.push(node.left);
            }
        }
        return list;
    }
}
